package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.dto.ChannelPageRequestDto;
import com.itheima.admin.mapper.AdChannelMapper;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.admin.service.AdChannelService;
import com.itheima.common.exception.GlobalExceptionHandler;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper,AdChannel>implements AdChannelService {
    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResultVo<AdChannel> pageList(ChannelPageRequestDto dto) {
        //设置分页参数
        IPage<AdChannel> pageInfo = new Page(dto.getPage(), dto.getSize());
        //构建查询条件
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        //查询名称--模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(dto.getName()), AdChannel::getName,dto.getName());
        //查询状态--精确查询
        queryWrapper.eq(null != dto.getStatus(),AdChannel::getStatus,dto.getStatus());

        //分页查询
        IPage<AdChannel> page = page(pageInfo, queryWrapper);

        return PageResultVo.pageResult(page.getCurrent(),
                page.getSize(),page.getTotal(),page.getRecords());
    }

    @Override
    public boolean saveChannel(AdChannel adChannel) {
        /*LocalDateTime now = LocalDateTime.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = sdf.format(now);*/
        if(null == adChannel.getAsDefault()){
            adChannel.setAsDefault(true);
        }
        adChannel.setAsDefault(false);
        return save(adChannel);
    }

    @Override
    public AdChannel findById(Long id) {
        return getById(id);
    }

    @Override
    public boolean updateChannelById(AdChannel adChannel) {
        AdChannel channel = getById(adChannel.getId());
        if(channel == null){
            throw new LeadNewsException();
        }
        return updateById(adChannel);
    }

    @Override
    public boolean deleteById(Long id) {
        //通过id查询数据库
        AdChannel adChannel = getById(id);
        adChannel.setStatus(false);
        return updateById(adChannel);
    }
}
